//
//  ServiceMotion.swift
//  home
//
//  Created by Yun Zeng on 2019/2/1.
//  Copyright © 2019 Yun Zeng. All rights reserved.
//

import UIKit

// 人体运动检测器
class ServiceSensorMotion {
    var service: Service
    
    // 是否有人，已经当前环境亮度
    var motion: HMCharacteristic
    var ambient: HMCharacteristic
    
    init? (service: Service) {
        if service.type != HMServiceType.motion.rawValue {
            return nil
        }
        
        guard let motion = service.findCharacteristic(type: .on),
            let ambient = service.findCharacteristic(type: .currentAmbientLightLevel) else {
            return nil
        }
        
        self.service = service
        self.motion = motion
        self.ambient = ambient
    }
    
    var motionValue: Int {
        get {
            if let value = self.motion.value?.toValueInt() {
                if value != 0 {
                    self.service.state = .highlight
                }
                return value
            }
            return 0
        }
    }
    
    var ambientValue: Int {
        get {
            if let value = self.ambient.value?.toValueInt() {
                return value
            }
            return 0
        }
    }
}

extension ServiceSensorMotion: ServiceCellDelegate {
    var icon: UIView {
        let imageValue = UIImageView(frame: ServiceCellView.iconSize)
        guard let icon = self.service.icon else {
            return imageValue
        }
        var imgSrc = ""
        if self.service.state == .offline || self.motionValue == 0 {
            imgSrc = "service-" + icon + "-close"
        } else {
            imgSrc = "service-" + icon + "-open"
        }
        imageValue.image = UIImage(named: imgSrc)
        return imageValue
    }
    
    var room: String {
        if let r = self.service.room {
            return r.name
        }
        return "默认房间"
    }
    
    var name: String {
        if self.service.name != "" {
            return self.service.name
        }
        return "请命名"
    }
    
    var state: Service.State {
        return self.service.state
    }
    
    var desc: String {
        if self.motionValue == 0 {
            return "无人 \(self.ambientValue)lux"
        }
        return "有人 \(self.ambientValue)lux"
    }
    
    func toggle() -> HomeAction? {
        return nil
    }
}








